package com.wswy.wzcx.widget

import android.content.Context
import android.support.constraint.ConstraintLayout
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import com.wswy.wzcx.R
import kotlinx.android.synthetic.main.layout_loading_status_btn.view.*

class LoadingButton : ConstraintLayout {


    constructor(context: Context) : this(context, null)

    constructor(context: Context, attribute: AttributeSet?) : this(context, attribute, 0)

    constructor(context: Context, attribute: AttributeSet?, defStyle: Int) : super(context, attribute, defStyle) {


        val typedArray = context.obtainStyledAttributes(attribute, R.styleable.LoadingButton)

        val text = typedArray.getText(R.styleable.LoadingButton_android_text)

        val bg = typedArray.getResourceId(R.styleable.LoadingButton_ld_background,0)

        //val enabled = typedArray.getBoolean(R.styleable.LoadingButton_android_enable,true)

        typedArray.recycle()

        View.inflate(context,R.layout.layout_loading_status_btn,this)

        if (!TextUtils.isEmpty(text)){
            tv_loading_status.text = text
        }

        if (bg >0){
            tv_bg.setBackgroundResource(bg)
        }

        isEnabled = false
    }

    fun normal(status:String?=null){
        loading_status.visibility = View.GONE
        if (!TextUtils.isEmpty(status)){
            tv_loading_status.text = status
        }
    }

    fun loading(loading:String?=null){
        loading_status.visibility = View.VISIBLE
        loading_status.loadLoading()
        if (!TextUtils.isEmpty(loading)){
            tv_loading_status.text = loading
        }
    }

    fun success(text:String?=null,block:(()->Unit)?=null){
        if (!TextUtils.isEmpty(text)){
            tv_loading_status.text = text
        }
        loading_status.loadSuccess{
            block?.invoke()
        }
    }

    fun fail(text:String?=null,block:(()->Unit)?=null){
        if (!TextUtils.isEmpty(text)){
            tv_loading_status.text = text
        }
        loading_status.loadFailure{
            block?.invoke()
        }
    }

    fun end(text: String?=null,block: (() -> Unit)?=null){
        if (!TextUtils.isEmpty(text)){
            tv_loading_status.text = text
        }
        loading_status.loadEnd()
        block?.invoke()
    }

    override fun setOnClickListener(l: OnClickListener?) {
        //super.setOnClickListener(l)
        tv_bg.setOnClickListener(l)
    }


    override fun setClickable(clickable: Boolean) {
        super.setClickable(clickable)
        tv_bg.isClickable = clickable
    }

    override fun setEnabled(enabled: Boolean) {
        super.setEnabled(enabled)

        tv_bg.isEnabled = enabled
    }

}